package com.tanhua.dubbo.server;

import cn.hutool.core.util.RandomUtil;
import org.springframework.retry.annotation.Backoff;
import org.springframework.retry.annotation.EnableRetry;
import org.springframework.retry.annotation.Recover;
import org.springframework.retry.annotation.Retryable;
import org.springframework.stereotype.Service;

import java.util.Random;

@Service
public class RetryService {
    //正常执行的业务方法
    //value :发生RuntimeException 异常开始重试，maxAttempts 需要重试次数为3
    //backoff 重试的策略， delay 停顿2秒，multiplier 默认0设置为2，则第一次重试为2秒，第二次为4秒，第三次为6秒。
    @Retryable(value = RuntimeException.class,
            maxAttempts = 3,
            backoff = @Backoff(delay = 2000L, multiplier = 2))
    public int execute(int max){
        int data = RandomUtil.randomInt(1, 99);
        System.out.println("生成：" + data);

        if (data < max) {
            throw new RuntimeException();
        }
        return data;


    }
    //重试三次失败后
    @Recover //全部重试失败后执行
    //Exception为RuntimeException 所以属于同一类
    public int recover(Exception e) {
        System.out.println("全部重试完成。。。。。");
        return 88; //返回默认
    }
}
